#!/usr/bin/python3
#******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
"""
This is a helper script for working with gitee.com
"""

import sys
import os
import json
import base64
import urllib
import urllib.request
import urllib.parse
import urllib.error
from datetime import datetime
import yaml


class Gitee(object):
    """
    Gitee is a helper class to abstract gitee.com api
    """
    def __init__(self):
        self.token = {}

        token_path = os.path.expanduser("~/.gitee_token.json")
        if os.path.exists(token_path):
            try:
                with open(token_path, "r") as f:
                    self.token = json.load(f)
            except json.JSONDecodeError:
                print("Unexpected UTF-8 BOM (decode using utf-8-sig)")
            except json.TypeError:
                print("the json object must be str, bytes or bytearray")
        else:
            print("gitee_token.json is not exist")

        self.headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW 64; rv:50.0) '\
                        'Gecko/20100101 Firefox/50.0'}
        self.src_openeuler_url = "https://gitee.com/src-openeuler/{repo}/raw/{br}/"
        self.advisor_url = "https://gitee.com/openeuler/openEuler-Advisor/raw/master/"
        self.time_format = "%Y-%m-%dT%H:%M:%S%z"

    def get_gitee(self, url, headers=None):
        """
        GET from gitee api
        """
        if headers is None:
            headers=self.headers

        try:
            req = urllib.request.Request(url=url, headers=headers)
            result = urllib.request.urlopen(req, timeout=5)
            return result.read().decode("utf-8")
        except urllib.error.HTTPError as e:
            print(url)
            print(str(e.code) + " " + e.reason)
            return None
        except urllib.error.URLError as e:
            print(url)
            print(e.reason)
            return None

    def get_gitee_json(self, url):
        """
        Get and load gitee json response
        """
        json_resp = []
        headers = self.headers.copy()
        headers["Content-Type"] = "application/json;charset=UTF-8"
        resp = self.get_gitee(url, headers)
        if resp:
            try:
                json_resp = json.loads(resp)
            except json.JSONDecodeError:
                print("Unexpected UTF-8 BOM (decode using utf-8-sig)")
            except json.TypeError:
                print("the json object must be str, bytes or bytearray")
            
        return json_resp

    def get_gitee_dict(self, url, param=""):
        """
        Get info  of gitee
        """
        dict_resp = []
        url += param

        try:
            token_param = "access_token={}".format(self.token["access_token"])
        except KeyError as ke:
            print('Key Not Found in token Dictionary:', ke)
            return dict_resp

        separator = "?"
        if param:
            separator = "&"
        url += separator + token_param
        dict_resp = self.get_gitee_json(url)

        return dict_resp

    def get_spec(self, pkg, branch="master"):
        """
        Get openeuler spec file for specific package
        """
        specurl = self.src_openeuler_url + "{repo}.spec"
        specurl = specurl.format(repo=pkg, br=branch)
        excpt = self.get_spec_exception(pkg)
        if excpt:
            specurl = urllib.parse.urljoin(specurl, os.path.join(excpt["dir"], excpt["file"]))
        resp = self.get_gitee(specurl)
        return resp

#################################
#       Get issue message
#################################
    def get_issues(self, pkg, prj="src-openeuler"):
        """
        List all open issues of pkg
        """
        issues_url = "https://gitee.com/api/v5/repos/{prj}/{pkg}/issues?".format(prj=prj, pkg=pkg)
        parameters = "state=open&sort=created&direction=desc&page=1&per_page=20"
        return self.get_gitee_json(issues_url + parameters)

    def get_issue_comments(self, pkg, prj="src-openeuler"):
        """
        Get comments of specific issue
        """
        issues_url = "https://gitee.com/api/v5/repos/{prj}/{pkg}/issues?".format(prj=prj, pkg=pkg)
        parameters = "number={num}&page=1&per_page=20&order=asc"
        return self.get_gitee_json(issues_url + parameters)

    def get_issue_merged_branches(self, issue_id, repo, owner="src-openeuler"):
        """
        Get merged branches of specific issue
        """
        issues_url = "https://gitee.com/api/v5/repos/{owner}/issues/{number}/pull_requests?"
        issues_url = issues_url.format(owner=owner, number=issue_id)
        param = "&repo={}".format(repo)
        return self.get_gitee_dict(issues_url, param)

if __name__ == "__main__":
    pass
